package com.basic.shiro;

import com.code.entity.User;
import com.code.service.IUserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;

//自定义Realm
@Slf4j
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    //授权：用来授予用户做的事情
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //AuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal(); //获取当前用户的认证
        //进行角色的添加和权限的添加。
        //info.addRole(user.getPower());//角色
        info.addStringPermissions(Arrays.asList(new String[]{"user,admin,area"})); //权限
        return info;
    }

    //认证：用来判断用户是否登录
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException,AccountException,UnknownAccountException {
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        //校验该用户是否存在
        User user = new User();
        String pass = null ;
        if(userToken != null){
            //获取password 先进性解密
           pass = String.valueOf(userToken.getPassword());
            user =  userService.checkedUserAndPass(userToken.getUsername(),pass);
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);
        //查询对象是否为null 说明这个人
        if(user== null){ //没有这个人
            //throw new UnknownAccountException(); // 抛出异常 UnknownAccountException
            throw new AccountException("帐号或密码不正确！");
        }

        //可以加密： md5 在破解风险 md5严值加密：不可逆
        //密码认证 shiro做，加密了
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");

    }
}
